#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>   
#define PORT 3490 		/* Server的端口 */
float shu;
struct occupy        
{
char name[20];      
 float a1,a2,a3,idle,a4,a5,a6,a7,a8,a9,a,cpu1,cpu2;  
};
float g_cpu_used;           
int cpu_num;               
void cal_occupy(struct occupy *, struct occupy *);  
int get_occupy(struct occupy *);             
int get_occupy (struct occupy *o) 
{
FILE *fd;         
int n;          
char buff[1024];  
fd = fopen ("/proc/stat", "r"); 
fgets (buff, sizeof(buff), fd); 
for(n=0;n<cpu_num;n++)          
{
fgets (buff, sizeof(buff),fd);
sscanf (buff, "%s %f %f %f %f %f %f %f %f %f %f", &o[n].name, &o[n].a1, &o[n].a2, &o[n].a3,&o[n].idle,&o[n].a4,&o[n].a5,&o[n].a6,&o[n].a7,&o[n].a8,&o[n].a9);
}
o[1].cpu1=o[1].a1+o[1].a2+o[1].a3+o[1].idle+o[1].a4+o[1].a5+o[1].a6+o[1].a7+o[1].a8+o[1].a9;
o[1].cpu2=o[2].a1+o[2].a2+o[2].a3+o[2].idle+o[2].a4+o[2].a5+o[2].a6+o[2].a7+o[2].a8+o[2].a9;
o[1].a=(o[2].idle-o[1].idle)/(o[1].cpu2-o[1].cpu1);
shu=o[1].a;
shu=shu/10;
if(shu<=0)
{
   shu=-shu;
}
fclose(fd); 
}

int main(int argc, char *argv[])
{
	int sockfd, numbytes;
	char buf[100];
        struct occupy ocpu[10];     
        int i;                    
        cpu_num = sysconf(_SC_NPROCESSORS_ONLN);  
	struct hostent *he;		/* 主机信息 */
	struct sockaddr_in their_addr; 	/* 对方地址信息 */
	if (argc != 2) {
		fprintf(stderr,"usage: client hostname\n");
		exit(1);
	}
        if ((he=gethostbyname(argv[1])) == NULL) { 
		/* get the host info */
		herror("gethostbyname");
		exit(1);
	}

	if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1) {
		perror("socket");
		exit(1);
	}

	their_addr.sin_family = AF_INET; 
	their_addr.sin_port = htons(PORT); 		/* short, NBO */
	their_addr.sin_addr = *((struct in_addr *)he->h_addr);
	bzero(&(their_addr.sin_zero), 8); 		/* 其余部分设成0 */

	if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
		perror("connect");
		exit(1);
	}
       while(1)
       {
           get_occupy(ocpu);    
           sprintf(buf,"%f",shu);                                                             
          if (send(sockfd, buf, sizeof(buf), 0) == -1) perror("send");
          sleep(1); 
       }
        close(sockfd); 	
        return 0;
}

